package com.org.devg.monitor.client;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.org.devg.monitor.client.aspect.MonitorWebAspect;
import com.org.devg.monitor.client.model.MonitorClientConfig;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import java.text.SimpleDateFormat;

@Configuration
@ComponentScan(basePackages = {"com.org.devg.monitor.client"})
@EnableConfigurationProperties(MonitorClientConfig.class)
@ConditionalOnWebApplication //web应用才生效
public class MonitorClientAutoConfiguration {

    private final MonitorClientConfig monitorClientConfig;

    public MonitorClientAutoConfiguration(MonitorClientConfig monitorClientConfig) {
        this.monitorClientConfig = monitorClientConfig;
    }

    @Bean
    public MonitorClientInit monitorClientInit() {
        MonitorClientInit monitorClientInit = new MonitorClientInit(monitorClientConfig);
        return monitorClientInit;
    }

    @Bean
    public MonitorWebAspect webAspect() {
        MonitorWebAspect monitorWebAspect = new MonitorWebAspect(monitorClientConfig);
        return monitorWebAspect;
    }

    private static final ObjectMapper mapper = new ObjectMapper();

    public static ObjectMapper getObjectMapper() {
        return mapper;
    }

    static {
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        mapper.configure(MapperFeature.PROPAGATE_TRANSIENT_MARKER, true);
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        mapper.registerModule(new JavaTimeModule());
    }
}
